/**
 * Copyright ©2016-2020 northkingbpo Corporation, All Rights Reserved
 * http://www.northkingbpo.net/
 */
package profile.hujia.simulation.data.common;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import profile.hujia.simulation.data.config.SystemConfig;

import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.List;

/**
 * class info
 *
 * @author hujia
 * @date 2019-06-12 14:57
 */
@Slf4j
@Data
public class ExcelFile {

    private HSSFWorkbook file;
    private HashMap<String, HSSFSheet> sheets;
    private String filePath;
    private HSSFSheet currentSheet;

    public ExcelFile() {
        sheets = new HashMap<>();
        currentSheet = null;
    }

    public void init() {
        file = new HSSFWorkbook();
        filePath = SystemConfig.EXCEL_FILE_PATH;
    }

    public void getSheet(String sheetName) {
        HSSFSheet sheet = null;
        if (sheets.isEmpty()) {
            sheet = file.createSheet(sheetName);
            sheets.put(sheetName, sheet);
        } else {
            sheet = sheets.get(sheetName);
            if (sheet == null) {
                sheet = file.createSheet(sheetName);
                sheets.put(sheetName, sheet);
            }
        }
        currentSheet = sheet;
    }

    public void setRowValue(List<String> values) {
        HSSFRow newRow = null;
        if (!values.isEmpty()) {
            Integer rowNumber = currentSheet.getLastRowNum();
            HSSFRow row = currentSheet.getRow(rowNumber);
            if (row != null) {
                ++rowNumber;
            }
            newRow = currentSheet.createRow(rowNumber++);
            for (int i = 0; i < values.size(); ++i) {
                newRow.createCell(i).setCellValue(values.get(i));
            }
        }
    }

    public void close() {
        try {
            FileOutputStream out = new FileOutputStream(filePath);
            file.write(out);
            out.close();
        } catch (Exception e) {
            log.error("error:" + e.getMessage());
        }
    }

}
